package com.ego.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ego.common.utils.CodecUtils;
import com.ego.common.utils.NumberUtils;
import com.ego.exception.enums.ExceptionEnum;
import com.ego.exception.exception.EgoException;
import com.ego.user.mapper.UserMapper;
import com.ego.user.pojo.User;
import com.ego.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Override
    public Boolean check(String data, Integer type) {

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        if (type == 1) {
            wrapper.eq("username",data);
        }else {
            wrapper.eq("phone",data);
        }
        Integer count = userMapper.selectCount(wrapper);
        return count==0;
    }

    @Override
    public void send(String phone) {
        try {
            //1.生成6位随机验证码
            String code = NumberUtils.generateCode(6);
            //2.存储到redis
            stringRedisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            //3.异步发送信息到mq
            amqpTemplate.convertAndSend("ego.sms.exchange", "sms.verify.code", phone + "&&&" + code);
        } catch (Exception e) {
            EgoException.error(log, ExceptionEnum.SMS_SEND_ERROR,e);
        }
    }

    @Override
    @Transactional
    public void register(User user, String code) {
        //校验验证码
        String redisCode = stringRedisTemplate.opsForValue().get(user.getPhone());
        if (!code.equals(redisCode)) {
            EgoException.error(log,ExceptionEnum.VERIFY_CODE_NOT_MATCHING);
        }
        //密码加密
        String password = CodecUtils.passwordBcryptEncode(user.getUsername(), user.getPassword());
        user.setPassword(password);
        user.setCreated(new Date());
        userMapper.insert(user);
    }

    @Override
    @Transactional(readOnly = true)
    public User findByUP(String username, String password) {

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        User user = userMapper.selectOne(queryWrapper);
        //校验密码是否正确
        if (CodecUtils.passwordConfirm(username+password,user.getPassword())) {
            return user;
        }
        return null;
    }
}
